const fetch = require('../../utils/fetch')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    category: {},
    shops: [],
    pageIndex: 1,
    pageSize: 10,
    query: '',
    hasMore: true
  },

  getShops() {
    //仅还有数据的时候才进行加载
    if (!this.data.hasMore) return
    let {
      pageIndex,
      pageSize,query
    } = this.data
    let param = {
      _page: pageIndex,
      _limit: pageSize,
      q:query
    }
    return fetch(`categories/${this.data.category.id}/shops`, param).then(res => {

      //将数据追加到数组上
      let shops = this.data.shops.concat(res.data)
      //获取总条数
      let total = parseInt(res.header['x-total-count'])

      //判断是否还有数据
      let hasMore = (pageIndex * pageSize) < total
      //页码自增
      pageIndex = pageIndex + 1
      this.setData({
        shops,
        pageIndex,
        hasMore
      })

    })
  },
  inputHandle(e) {
   this.setData({
     query:e.detail.value
   })
  },
  searchHandle(){
    this.setData({
      pageIndex:1,
      shops:[],
      hasMore:true
    })
    this.getShops()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取当前分类
    let cat = options.cat
    fetch(`categories/${cat}`).then(res => {
      this.setData({
        category: res.data
      })
      //设置导航条
      wx.setNavigationBarTitle({
        title: this.data.category.name
      })
      //获取商户列表
      this.getShops()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //设置导航栏标题
    if (this.data.category.name) {
      wx.setNavigationBarTitle({
        title: this.data.category.name,
      })
    }
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      shops: [],
      hasMore: true,
      pageIndex: 1
    })
    this.getShops().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getShops()
  },


})